package henu.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import henu.bean.Schedule;
import henu.dao.IScheduleDao;

public class ScheduleDaoImpl implements IScheduleDao{
	protected QueryRunner qr = new QueryRunner();
	private int row = 0;
	public ScheduleDaoImpl(QueryRunner qr){
		super();
		this.qr = qr;
	}
	@Override
	public int add(Schedule sche) {
		String sql = "insert into tb_schedule(fCourseNum,fCourseName,fCourseYear,fCourseTerm,fGrade) values(?,?,?,?,?)";
		Object[] param = {sche.getfCourseNum(),sche.getfCourseName(),sche.getfCourseYear(),sche.getfCourseTerm(),sche.getfGrade()};
		try {
			row = qr.update(sql, param);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return row;
	}

	@Override
	public int delete(int id) {
		String sql = "delete from tb_schedule where id=?";
		Object[] param = {id};
		try {
			row = qr.update(sql,param);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return row;
	}

	@Override
	public int update(Schedule sche) {
		String sql = "update tb_schedule set fCourseName=?,fCourseYear=?,fCourseTerm=?,fGrade=? where fCourseNum=?";
		Object[] param = {sche.getfCourseName(),sche.getfCourseYear(),sche.getfCourseTerm(),sche.getfGrade(),sche.getfCourseNum()};
		try {
			row = qr.update(sql, param);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return row;
	}

	@Override
	public Schedule select(String coursename) {
		String sql = "select * from tb_schedule where fCourseName=?";
		Object[] param = {coursename};
		Schedule sche = null;
		try {
			sche = qr.query(sql, param, new BeanHandler<>(Schedule.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sche;
	}

	@Override
	public List<Schedule> getAll() {
		String sql = "select * from tb_schedule";
		List<Schedule> schelist = null;
		try {
			schelist = qr.query(sql, new BeanListHandler<>(Schedule.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return schelist;
	}

}
